package service

import (
	"context"
	"fmt"
	"shop-src/basic/config"
	__ "shop-src/basic/proto"
	"shop-src/handler/model"
)

type Server struct {
	__.UnimplementedShopServer
}

// ShopAdd 商品添加
func (s *Server) ShopAdd(_ context.Context, in *__.ShopAddReq) (*__.ShopAddResp, error) {
	//参数校验
	if in.Name == "" {
		return nil, fmt.Errorf("商品名称违禁词检查")
	}
	//校验价格
	if in.Price < 0 {
		return nil, fmt.Errorf("价格不能为负数")
	}
	//库存为非负数
	if in.Number < 0 {
		return nil, fmt.Errorf("库存不能为非负数")
	}
	var shop model.Shop
	shop = model.Shop{
		Name:   in.Name,
		Price:  float64(in.Price),
		Number: int(in.Number),
		Images: in.Images,
		Status: int(in.Status),
	}
	config.DB.Create(&shop)
	return &__.ShopAddResp{
		Success: true,
		Message: "商品添加成功",
		ShopId:  int64(shop.ID),
	}, nil
}

func (s *Server) DisPlayAdd(_ context.Context, in *__.DisPlayAddReq) (*__.DisPlayAddResp, error) {
	var disp model.Display
	err := config.DB.Model(&model.Display{}).Where("disName=?", in.DisName).First(&disp).Error
	if err != nil {
		return nil, fmt.Errorf("橱窗分类名称已存在")
	}
	disp = model.Display{
		DisName: in.DisName,
		ShopId:  uint(in.ShopId),
	}
	config.DB.Create(&disp)
	return &__.DisPlayAddResp{
		Success:   true,
		Message:   "橱窗分类添加成功",
		DisPlayId: int64(disp.ID),
	}, nil
}

func (s *Server) OrderAdd(_ context.Context, in *__.OrderAddReq) (*__.OrderAddResp, error) {

	//参数校验
	if in.ShopId == 0 || in.UserId == 0 || in.Status == 0 {
		return nil, fmt.Errorf("订单参数不能为空")
	}

	var order model.Order
	order = model.Order{
		ShopId: uint(in.ShopId),
		UserId: uint(in.UserId),
		Status: int(in.Status),
	}
	config.DB.Create(&order)
	return &__.OrderAddResp{
		Success: true,
		Message: "订单商品添加成功",
		OrderId: int64(order.ID),
	}, nil
}
